#include"mystdio.h"
#include<stdlib.h>
#include<sys/types.h>
#include <sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
mFILE* mfopen(const char* filename,const char* mode)
{
  // 封装 system call open打开文件 
  int fd = -1;
  if(strcmp(mode,"r") == 0)
  {
   fd = open(filename,O_RDONLY);
  }
  else if(strcmp(mode,"w") == 0)
  {
    fd = open(filename,O_WRONLY | O_CREAT | O_TRUNC,0666);
  }
  else if(strcmp(mode,"a") == 0)
  {
     fd = open(filename,O_WRONLY | O_CREAT | O_TRUNC,0666);
  }
  //fd fail
  if(fd < 0)
    return NULL;
  // file open fail 文件打开失败
  mFILE* mf = (mFILE*)malloc(sizeof(mFILE));
  if(!mf)
  {
    close(fd);
    return NULL;
  }
  //mFILE状态
 mf->fileno = fd;
 mf->flag = FLUSH_LINE;
 mf->cap = SIZE;
 mf->size = 0;
 
 return mf; 
}

//  本质是写到内核缓冲区
void mfflush(mFILE* stream)
{
  if(stream->size > 0)
  {
    //write是将数据写到内核文件的文件缓冲区中
    write(stream->fileno,stream->outbuffer,stream->size);
    //刷新到外设
    fsync(stream->fileno);
    stream->size = 0;
  }
}

//myfwrite就做拷贝
int mfwrite(const void* ptr,int num,mFILE* stream)
{
  //1.拷贝
  memcpy(stream->outbuffer + stream->size , ptr,num);
  stream->size += num;
  //2.检测是否刷新
  if(stream->flag == FLUSH_LINE && stream->size > 0  && stream->outbuffer[stream->size-1] == '\n')
  {
     mfflush(stream);
  }
  return num;
}


void mfclose(mFILE* stream)
{
  //检测有效字符个数是否大于0 大于0就刷新
  if(stream->size > 0)
  {
    mfflush(stream);
  }
  //刷新之后关闭文件
  close(stream->fileno);
}
